﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.Hr;
using ESOL.Business.Sec;

namespace ESOL.WinUI.Sales
{
    public partial class frmManageSalesQuoteOrder : BaseForm.frmBaseMdiBusinessForm
    {
        #region Variable
        private SalesQuoteOrderEntity mSelectedSalesQuoteOrder;
        #endregion

        #region Constructor
        public frmManageSalesQuoteOrder()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbCurrency, "CS", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbDeliveryWay, "DW", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPackageType, "PT", true);
            
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colCURRENCY, "CS", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colSTATUS, "STATUS", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private string GetCondition()
        {
            string condition = "";
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                MstCustomerEntity customer = (MstCustomerEntity)txtCustomer.Tag;
                condition += " AND QO.CUSTOMER_ID = '" + customer.CustomerId + "' ";
            }
            if (string.IsNullOrEmpty(txtQuoteCode.Text) == false)
            {
                condition += " AND QO.QUOTE_ORDER_CODE LIKE '%" + txtQuoteCode.Text + "%'";
            }
            if (string.IsNullOrEmpty(cmbCurrency.Text) == false && cmbCurrency.SelectedValue != null)
            {
                condition += " AND QO.CURRENCY = '" + cmbCurrency.SelectedValue.ToString() + "'";
            }
            if (string.IsNullOrEmpty(cmbStatus.Text) == false && cmbStatus.SelectedValue != null)
            {
                condition += " AND QO.STATUS = '" + cmbStatus.SelectedValue.ToString() + "'";
            }
            if (string.IsNullOrEmpty(cmbDeliveryWay.Text) == false && cmbDeliveryWay.SelectedValue != null)
            {
                condition += " AND QO.TRANSPORT_TYPE = '" + cmbDeliveryWay.SelectedValue.ToString() + "'";
            }
            if (dtpQuoteDate.EditValue!=null)
            {
                condition += " AND QO.QUOTE_DATE >= CONVERT(DATETIME,'" + ((DateTime)dtpQuoteDate.EditValue).ToString("yyyy-MM-dd") + "')";
            }
            if (dtpQuoteDateTo.EditValue != null)
            {
                condition += " AND QO.QUOTE_DATE <= CONVERT(DATETIME,'" + ((DateTime)dtpQuoteDateTo.EditValue).ToString("yyyy-MM-dd") + "')";
            }
            if (string.IsNullOrEmpty(cmbPackageType.Text) == false && cmbPackageType.SelectedValue != null)
            {
                condition += " AND QO.PACKAGE_TYPE = '" + cmbPackageType.SelectedValue.ToString() + "'";
            }


            List<MstCustomerEntity> customers = new List<MstCustomerEntity>();
            //获得用户对应的角色的所有子角色
            SecUserEntity user = ESOL.Business.Sec.SecUserBs.GetUserByID(Common.CommonParameter.CurrentUser.UserId);
            List<SecUserRoleEntity> userroles = SecUserRoleBs.GetSecUserRolesByUserID(user.UserId);
            List<SecRoleEntity> roles = new List<SecRoleEntity>();
            foreach (SecUserRoleEntity userrole in userroles)
            {
                roles.AddRange(SecRoleBs.GetChildrenRolesForID(userrole.RoleId, null));
            }
            //根据子角色获取所有对应的用户
            List<MstPersonEntity> persons = new List<MstPersonEntity>();
            if (roles.Count != 0)
            {
                persons = MstPersonBs.GetPersonForRoles(roles);
            }
            persons.Add(Common.CommonParameter.CurrentUser.PersonEntity);
            customers = MstPersonCustomerBs.GetCustomerByPersons(persons);
            if (customers.Count == 0)
                return condition;
            condition += " AND QO.CUSTOMER_ID IN (";
            foreach (MstCustomerEntity m in customers)
            {
                condition += "'" + m.CustomerId + "',";
            }
            condition = condition.Substring(0, condition.Length - 1);
            condition += ")";
            if (txtQuotePerson.Tag != null && txtQuotePerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                MstPersonEntity entity = (MstPersonEntity)txtQuotePerson.Tag;
                condition += " AND QO.QUOTE_PERSON = '" + entity.PersonId + "' ";
            }
            else
            {
                condition += " AND QO.QUOTE_PERSON IN (";
                foreach (MstPersonEntity person in persons)
                {
                    condition += "'" + person.PersonId + "',";
                }
                condition = condition.Substring(0, condition.Length - 1);
                condition += ")";
            }
            return condition;
        }

        private void BindDataGrid()
        {
            string condition = GetCondition();
            string rowCount = txtRowCount.Text;
            string orderBy = "QUOTE_ORDER_CODE DESC";
            DataTable dt = SalesQuoteOrderBs.GetByCondition(condition, orderBy, rowCount);
            gvMain.DataSource = dt;
        }

        private void BindDetailGrid(string quoteOrderID)
        {
            if (string.IsNullOrEmpty(quoteOrderID))
            {
                gvDetail.DataSource = null;
                return;
            }
            DataSet ds = SalesQuoteItemBs.GetDataSetByQuoteOrderID(quoteOrderID);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvDetail.DataSource = null;
            }
            gvDetail.DataSource = ds.Tables[0];
        }

        private void ResetButtonsEnable()
        {
            btnModify.Enabled = false;
            btnDelete.Enabled = false;
            btnSubmit.Enabled = false;
            btnApprove.Enabled = false;
            btnPrint.Enabled = false;
            if (mSelectedSalesQuoteOrder == null)
            {
                return;
            }
            if (mSelectedSalesQuoteOrder.Status == NormalStatus.STATUS01.ToString()
                || mSelectedSalesQuoteOrder.Status == NormalStatus.STATUS02.ToString()
                || mSelectedSalesQuoteOrder.Status == NormalStatus.STATUS04.ToString())
            {
                btnModify.Enabled = true;
                btnDelete.Enabled = true;
                btnApprove.Enabled = true;
            }
            else if (mSelectedSalesQuoteOrder.Status == NormalStatus.STATUS03.ToString())
            {
                btnPrint.Enabled = true;
            }
            else if (mSelectedSalesQuoteOrder.Status == NormalStatus.STATUS05.ToString())
            {
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            mCanQueryOtherPerson = UICommon.UICommonFunctions.CheckPersonRight(RoleCategory.销售);
            BindComboBox();
            BindDataGrid();
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow dr = gridView1.GetDataRow(e.RowHandle);
            mSelectedSalesQuoteOrder = new SalesQuoteOrderEntity(dr);
            BindDetailGrid(mSelectedSalesQuoteOrder.QuoteOrderId);
            ResetButtonsEnable();
        }

        protected override void Click_View()
        {
            if (mSelectedSalesQuoteOrder == null)
            {
                MessageBox.Show("请选择一个报价单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainSalesQuoteOrder frm = new frmMaintainSalesQuoteOrder();
            frm.ThisActionType = ActionType.View;
            frm.SelectedSalesQuoteOrder = mSelectedSalesQuoteOrder;
            frm.ShowDialog();
        }

        protected override void Click_Delete()
        {
            if (mSelectedSalesQuoteOrder == null)
            {
                MessageBox.Show("请选择一个报价单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult dr = MessageBox.Show("是否删除选中报价单？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.No)
            {
                return;
            }
            try
            {
                mSelectedSalesQuoteOrder.Status = NormalStatus.STATUS05.ToString();
                mSelectedSalesQuoteOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                mSelectedSalesQuoteOrder.LastModifiedDate = DateTime.Now;
                bool successful = SalesQuoteOrderBs.UpdateSalesQuoteOrder(mSelectedSalesQuoteOrder);
                if (successful)
                {
                    MessageBox.Show("删除成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    BindDataGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        protected override void Click_Submit()
        {
            if (mSelectedSalesQuoteOrder == null)
            {
                MessageBox.Show("请选择一个报价单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult dr = MessageBox.Show("是否送审选中报价单？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.No)
            {
                return;
            }
            try
            {
                mSelectedSalesQuoteOrder.Status = NormalStatus.STATUS02.ToString();
                mSelectedSalesQuoteOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                mSelectedSalesQuoteOrder.LastModifiedDate = DateTime.Now;
                bool successful = SalesQuoteOrderBs.UpdateSalesQuoteOrder(mSelectedSalesQuoteOrder);
                if (successful)
                {
                    MessageBox.Show("送审成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    BindDataGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        protected override void Click_Approve()
        {
            if (mSelectedSalesQuoteOrder == null)
            {
                MessageBox.Show("请选择一个报价单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainSalesQuoteOrder frm = new frmMaintainSalesQuoteOrder();
            frm.ThisActionType = ActionType.Approve;
            frm.SelectedSalesQuoteOrder = mSelectedSalesQuoteOrder;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        protected override void Click_Modify()
        {
            if (mSelectedSalesQuoteOrder == null)
            {
                MessageBox.Show("请选择一个报价单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainSalesQuoteOrder frm = new frmMaintainSalesQuoteOrder();
            frm.ThisActionType = ActionType.Modify;
            frm.SelectedSalesQuoteOrder = mSelectedSalesQuoteOrder;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        protected override void Click_New()
        {
            frmMaintainSalesQuoteOrder frm = new frmMaintainSalesQuoteOrder();
            frm.ThisActionType = ActionType.New;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        protected override void Click_Query()
        {
            BindDataGrid();
        }

        protected override void Click_Print()
        {
            if (mSelectedSalesQuoteOrder == null)
            {
                MessageBox.Show("请选择一个报价单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //List<SalesQuoteOrderEntity> list = new List<SalesQuoteOrderEntity>();
            //list.Add(mSelectedSalesQuoteOrder);
            //frmFindPrinter frmPrinter = new frmFindPrinter();
            //if (frmPrinter.ShowDialog() == DialogResult.OK)
            //{
            //    frmPrintSalesQuoteOrder frm = new frmPrintSalesQuoteOrder(list);
            //    frm.SelectedPrinterName = frmPrinter.SelectedPrinterName;
            //    frm.DocumentName = mSelectedSalesQuoteOrder.QuoteOrderCode;
            //    frm.Print();
            //}
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                txtCustomer.Text = frm.SelectedCustomer.CustomerName;
                txtCustomer.Tag = frm.SelectedCustomer;
            }
            else
            {
                txtCustomer.Text = "";
                txtCustomer.Tag = null;
            }
        }

        private void txtQuotePerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtQuotePerson.Text = frm.SelectedPerson.NameCn;
                txtQuotePerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtQuotePerson.Text = "";
                txtQuotePerson.Tag = null;
            }
        }

        #endregion

    }
}
